const { getUserTaskCheckInPage, taskStatistics, taskCheckInRecordPage } = require('../../../utils/task');
const { formatHHmm, formatDateTimeNoSeconds } = require('../../../utils/date');
import * as echarts from '../../../components/ec-canvas/echarts';
// 假设有 getCheckInTrendData 接口
// import { getCheckInTrendData } from '../../utils/task';

let innerAudio = null;

Page({
  data: {
    taskId: '',
    statistics: {
      // 有效打卡数
      finishCheckIns: 0,
      // 无效打卡数
      overdueCheckIns: 0,
      // 参与人数
      quoteCount: 0,
      completionRate: '0%',
      earliestCheckIn: '',
      latestCheckIn: ''
    },
    recordList: [],
    page: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    showMediaModal: false,
    previewMediaUrl: '',
    previewMediaType: '',
    showHelpModal: false,
    trendChartOption: {
      lazyLoad: true
    },
    trendData: [],
    ec: {
      option: { /* 你的 ECharts 配置 */ }
    },
    isAudioPlaying: false,
    audioCurrentTime: 0,
    audioDuration: 1,
    isAudioSliderDragging: false,
    wasAudioPlayingBeforeDrag: false,
  },

  onLoad(options) {
    console.log('打卡记录页面加载，参数:', options);
    this.setData({ taskId: options.taskId });
    this.initPageData();
  },

  /**
   * 初始化页面数据
   */
  async initPageData() {
      // 然后加载统计数据
      await this.loadStatistics();
      // 最后加载打卡记录
      await this.loadRecordList(true);
  },

  /**
   * 加载统计数据
   */
  async loadStatistics() {
    try {
      console.log('开始加载统计数据，任务ID:', this.data.taskId);
      
      // 调用真实的统计数据接口
      const statisticsData = await taskStatistics(this.data.taskId);
      console.log('获取到的统计数据:', statisticsData);
      
      // 处理返回的数据，确保字段匹配
      const processedStatistics = {
        finishCheckIns: statisticsData.finishCheckIns || 0,
        overdueCheckIns: statisticsData.overdueCheckIns || 0,
        quoteCount: statisticsData.quoteCount || 0,
        completionRate: statisticsData.completionRate || '0%',
        earliestCheckIn: statisticsData.earliestCheckIn || '',
        latestCheckIn: statisticsData.latestCheckIn || ''
      };
      
      // 保存趋势数据
      const trendDataList = statisticsData.trendDataList || [];
      this.setData({ statistics: processedStatistics, trendData: trendDataList });
      
      // 加载完统计数据后初始化折线图
      this.initTrendChart();
      
    } catch (e) {
      console.error('加载统计数据失败:', e);
      
      // 如果接口调用失败，使用默认数据
      const defaultStatistics = {
        finishCheckIns: 0,
        overdueCheckIns: 0,
        quoteCount: 0,
        completionRate: '0%',
        earliestCheckIn: '',
        latestCheckIn: ''
      };
      
      this.setData({ statistics: defaultStatistics });
      
      wx.showToast({ 
        title: e.data?.msg || '加载统计数据失败', 
        icon: 'none',
        duration: 2000
      });
    }
  },

  /**
   * 加载打卡记录列表
   */
  async loadRecordList(reset = false) {
    if (this.data.loading || (!this.data.hasMore && !reset)) return;
    
    this.setData({ loading: true });
    const current = reset ? 1 : this.data.page;
    
    try {
      console.log('开始加载打卡记录，用户任务ID:', this.data.taskId, '页码:', current);
      
      // 调用真实的打卡记录接口
      const res = await taskCheckInRecordPage(this.data.taskId, current, this.data.pageSize);
      console.log('获取到的打卡记录:', res);
      
      const newRecords = res.records || [];
      const records = reset ? newRecords : this.data.recordList.concat(newRecords);
      
      // 格式化记录数据
      const formattedRecords = records.map(item => ({
        id: item.id,
        checkInTime: item.checkInTime,
        remark: item.checkInDesc || '',
        mediaType: item.mediaType || '',
        mediaPath: item.mediaPath ? (item.mediaPath.startsWith('http') ? item.mediaPath : (prefix + item.mediaPath)) : '',
        state: item.state,
        userName: item.userName || item.nickName || '未知用户',
        avatar: item.avatar || item.userAvatar || '/assets/avatar.png',
        time: formatDateTimeNoSeconds(item.checkInTime).split(' ')[1],
        date: formatDateTimeNoSeconds(item.checkInTime).split(' ')[0],
        checkInTime: formatHHmm(item.checkInTime),
        checkInDate: item.checkInDate,
        stateText: this.getStateText(item.state),
        stateClass: item.state
      }));

      this.setData({
        recordList: formattedRecords,
        page: current + 1,
        hasMore: newRecords.length >= this.data.pageSize,
        loading: false
      });
      
      console.log('打卡记录加载成功，当前页:', current, '记录数:', formattedRecords.length);
    } catch (e) {
      console.error('加载打卡记录失败:', e);
      this.setData({ loading: false });
      wx.showToast({ 
        title: e.data?.msg || '加载打卡记录失败', 
        icon: 'none',
        duration: 2000
      });
    }
  },

  /**
   * 获取状态文本
   */
  getStateText(state) {
    const stateMap = {
      'finish': '已完成',
      'overdue': '已过期',
      'quit': '已退出'
    };
    return stateMap[state] || '未知';
  },

  /**
   * 加载更多
   */
  onLoadMore() {
    this.loadRecordList(false);
  },

  /**
   * 预览媒体
   */
  previewMedia(e) {
    const { url, type } = e.currentTarget.dataset;
    console.log('预览媒体:', { url, type });
    if (type === 'image') {
      const images = this.data.recordList
        .filter(item => item.mediaType === 'image' && item.mediaPath)
        .map(item => item.mediaPath);
      wx.previewImage({
        current: url,
        urls: images.length ? images : [url]
      });
    } else if (type === 'video') {
      this.setData({
        showMediaModal: true,
        previewMediaUrl: url,
        previewMediaType: type
      });
    } else if (type === 'audio') {
      // 销毁旧实例
      if (innerAudio) {
        innerAudio.destroy();
        innerAudio = null;
      }
      innerAudio = wx.createInnerAudioContext();
      innerAudio.src = url;
      innerAudio.autoplay = false;
      innerAudio.obeyMuteSwitch = false;
      innerAudio.onCanplay(() => {
        setTimeout(() => {
          this.setData({
            audioDuration: innerAudio.duration || 1
          });
        }, 200);
      });
      innerAudio.onTimeUpdate(() => {
        if (!this.data.isAudioSliderDragging) {
          this.setData({
            audioCurrentTime: innerAudio.currentTime
          });
        }
      });
      innerAudio.onEnded(() => {
        this.setData({ isAudioPlaying: false, audioCurrentTime: 0 });
      });
      this.setData({
        showMediaModal: true,
        previewMediaUrl: url,
        previewMediaType: type,
        isAudioPlaying: false,
        audioCurrentTime: 0,
        audioDuration: 1,
        isAudioSliderDragging: false,
        wasAudioPlayingBeforeDrag: false
      });
    }
  },

  /**
   * 切换音频播放/暂停
   */
  toggleAudioPlay() {
    if (!innerAudio) return;
    if (this.data.isAudioPlaying) {
      innerAudio.pause();
      this.setData({ isAudioPlaying: false });
    } else {
      innerAudio.play();
      this.setData({ isAudioPlaying: true });
    }
  },

  /**
   * 监听音频元数据加载
   */
  onAudioLoadedMetaData(e) {
    let duration = Number(e.detail.duration) || 1;
    if (duration < 1) duration = 1;
    this.setData({
      audioDuration: duration
    });
  },

  /**
   * 监听音频播放进度
   */
  onAudioTimeUpdate(e) {
    if (!this.data.isAudioSliderDragging) {
      this.setData({
        audioCurrentTime: Number(e.detail.currentTime)
      });
    }
  },

  /**
   * 拖动进度条
   */
  onAudioSliderChange(e) {
    const value = Number(e.detail.value);
    if (innerAudio) {
      innerAudio.seek(value);
      if (this.data.isAudioPlaying) {
        innerAudio.play();
      }
    }
    this.setData({
      audioCurrentTime: value,
      isAudioSliderDragging: false
    });
  },
  onAudioSliderChanging(e) {
    this.setData({
      isAudioSliderDragging: true,
      audioCurrentTime: Number(e.detail.value)
    });
  },

  /**
   * 关闭媒体预览
   */
  closeMediaModal() {
    if (innerAudio) {
      innerAudio.stop();
      innerAudio.destroy();
      innerAudio = null;
    }
    this.setData({
      showMediaModal: false,
      previewMediaUrl: '',
      previewMediaType: ''
    });
  },

  /**
   * 阻止事件冒泡
   */
  stopPropagation() {
    // 阻止事件冒泡
  },

  /**
   * 显示帮助弹窗
   */
  showHelpModal() {
    this.setData({ showHelpModal: true });
  },

  /**
   * 关闭帮助弹窗
   */
  closeHelpModal() {
    this.setData({ showHelpModal: false });
  },

  /**
   * 头像加载错误处理
   */
  onAvatarError(e) {
    const index = e.currentTarget.dataset.index;
    const recordList = this.data.recordList;
    if (recordList[index]) {
      recordList[index].avatar = '/assets/avatar.png';
      this.setData({ recordList });
    }
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.loadStatistics();
    this.loadRecordList(true).then(() => {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 分享
   */
  onShareAppMessage() {
    return {
      title: '我的打卡记录',
      path: `/pages/task-check-in-record/task-check-in-record?taskId=${this.data.taskId}`
    };
  },

  onReady() {
    this.initTrendChart();
  },

  async initTrendChart() {
    // 用接口返回的 trendData
    const trendData = this.data.trendData || [];
    // 适配 ECharts 格式
    const chartData = trendData.map(item => ({
      date: item.checkInDate.slice(5), // 只取 MM-DD
      count: item.checkInCount
    }));

    this.selectComponent('#trendChart').init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, { width, height, devicePixelRatio: dpr });
      canvas.setChart(chart);
      this.setTrendChartOption(chart, chartData);
      this.trendChart = chart;
      return chart;
    });
  },

  setTrendChartOption(chart, trendData) {
    const option = {
      color: ['#4f8cff'],
      tooltip: { trigger: 'axis' },
      grid: { left: '6%', right: '6%', bottom: '10%', top: '16%', containLabel: true },
      xAxis: {
        type: 'category',
        data: trendData.map(d => d.date),
        boundaryGap: false,
        axisLabel: { color: '#888', fontSize: 10 }
      },
      yAxis: {
        type: 'value',
        minInterval: 1,
        axisLabel: { color: '#888', fontSize: 10 }
      },
      series: [{
        name: '打卡人数',
        type: 'line',
        data: trendData.map(d => d.count),
        smooth: true,
        areaStyle: { color: 'rgba(79,140,255,0.12)' },
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: { width: 3 }
      }]
    };
    chart.setOption(option);
  },

  onUnload() {
    if (innerAudio) {
      innerAudio.stop();
      innerAudio.destroy();
      innerAudio = null;
    }
  },
}); 